package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.dubbo.utils.TimeLineService;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.MovementTimeLine;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.SampleOperation;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@DubboService
public class MovementApiImpl implements MovementApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private TimeLineService timeLineService;

    //发布动态
    public String save(Movement movement) {
        //1、保存动态数据
        mongoTemplate.save(movement);
        ObjectId movementId = movement.getId();
        Long userId = movement.getUserId();
        //2、保存好友-动态关系数据--以多线程处理
        timeLineService.saveTimeLine(userId,movementId);
        return movement.getId().toHexString();
    }

    //根据用户id，查询动态列表
    public List<Movement> findByUserId(Long userId, Integer page, Integer pagesize) {
        //1、创建Creiteria对象
        Criteria criteria = Criteria.where("userId").is(userId).and("state").is(1);
        //2、创建Query
        Query query = Query.query(criteria)
                           .with(Sort.by(Sort.Order.desc("created")))
                           .limit(pagesize)
                           .skip((page-1) * pagesize);
        //3、查询列表
        return mongoTemplate.find(query,Movement.class);
    }

    //根据好友id，查询动态列表
    public List<Movement> findByFriendId(Long friendId, Integer page, Integer pagesize) {
        //1、分页查询关系表数据
        Criteria timeLineCriteria = Criteria.where("friendId").is(friendId);
        Query lineQuery = Query.query(timeLineCriteria)
                .with(Sort.by(Sort.Order.desc("created")))
                .limit(pagesize)
                .skip((page - 1) * pagesize);
        List<MovementTimeLine> list = mongoTemplate.find(lineQuery, MovementTimeLine.class);
        //2、获取关系表数据中的所有动态id
//        List<ObjectId> ids = new ArrayList<>();
//        for (MovementTimeLine timeline : list) {
//            ids.add(timeline.getMovementId());
//        }
        //list集合，提取的属性字段，属性字段的类型
        List<ObjectId> ids = CollUtil.getFieldValues(list, "movementId", ObjectId.class);//从list集合中获取指定的属性，构造新的集合
        //3、查询动态表，根据多个动态id，查询动态详情   id in (xxxx)
        Criteria criteria = Criteria.where("id").in(ids).and("state").is(1);
        Query query = Query.query(criteria);
        return mongoTemplate.find(query,Movement.class);
    }

    //根据动态id，分页查询数据  where id in（）
    public List<Movement> findByIds(String[] movementIds, Integer page, Integer pagesize) {
        Criteria criteria = Criteria.where("id").in(movementIds).and("state").is(1); //mongodb对于主键在做  is，in查询时，不需要转化成ObjectId
        Query query = Query.query(criteria).skip((page - 1) * pagesize).limit(pagesize);
        return mongoTemplate.find(query,Movement.class);
    }

    //随机获取,统计（使用频次不多）
    public List<Movement> randomMovement(Integer counts) {

        //定义统计类型
        SampleOperation operation = Aggregation.sample(counts);//随机获取

        //设置统计的方式
        TypedAggregation<Movement> aggregation = TypedAggregation.newAggregation(Movement.class,
                operation);

        //统计，将统计结果封装到了results对象中
        AggregationResults<Movement> results = mongoTemplate.aggregate(aggregation, Movement.class);

        //从封装对象中获取统计结果
        return results.getMappedResults();
    }

    //根据id查询
    public Movement findById(String movementId) {
        //传递String有些方法，直接使用
        return mongoTemplate.findById(new ObjectId(movementId),Movement.class);
    }

    @Override
    public void updateState(String movementId, Integer state) {
        Criteria criteria = Criteria.where("id").is(new ObjectId(movementId));
        Query query = Query.query(criteria);

        Update update = new Update();
        update.set("state",state);

        mongoTemplate.updateFirst(query,update,Movement.class);
    }

    @Override
    public PageResult findAll(Integer page, Integer pagesize, Long userId, Integer state) {
        //1、构建Criteria
        Criteria criteria = new Criteria();
        if(userId != null) {
            criteria.and("userId").is(userId);
        }
        if(state != null) {
            criteria.and("state").is(state);
        }
        //2、构建Query
        Query query = Query.query(criteria);
        //3、查询总数
        long count = mongoTemplate.count(query, Movement.class);
        //4、设置分页参数
        query.with(Sort.by(Sort.Order.desc("created")))
             .skip((page - 1) * pagesize)
             .limit(pagesize);
        //5、查询数据列表
        List<Movement> list = mongoTemplate.find(query, Movement.class);

        return new PageResult(page,pagesize,count,list);
    }
}
